import React from 'react';
import socketIO from 'socket.io-client';
import './index.scss';

import Chat from "./pages/chat";
import User from "./pages/user";
import localStorage from "./helper/ls";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      socket: null,
      user: null
    };
  }

  componentDidMount() {
    this.connectSocket();
    const user = localStorage.get('user');
    if (user) {
      this.setState({user});
    }
  }

  connectSocket = () => {
    const socket = socketIO('ws://localhost:7000', {
      path: '/v1/ws/chat2'
    });
    socket.on('connect', () => {
      console.log('已建立连接...');
    });

    socket.on('disconnect', e => {
      console.log('已经断开连接...');
    });

    this.setState({socket});
  };

  check = () => {
    const {socket} = this.state;
    console.log('检查 WebSocket 连接...', socket);
    if (!socket || socket.readyState === WebSocket.CLOSED) {
      this.connectSocket();
    } else {
      console.log('没有 ws 或者 socket 已经关闭...');
    }
  };

  handleUserLogin = (data) => {
    console.log('---', data);
    this.setState({user: data});
  }

  handleUserLogout = () => {
    this.setState({user: null});
    localStorage.remove('user');
  }

  render() {
    return (
      <div style={{margin: 20}}>
        {
          !this.state.user && <User handleUserLogin={this.handleUserLogin}/>
        }

        {
          this.state.user && <Chat
            socket={this.state.socket}
            handleUserLogout={this.handleUserLogout}
          />
        }
      </div>
    );
  }
}

export default App;
